from django import forms
from django.core.exceptions import ValidationError

from web.forms.bootstrapbase import BootStrapForm
from web import models
from utils.tencent.cos import CosTencent


class FileFolderModelForm(BootStrapForm, forms.ModelForm):
    """ 创建文件夹的ModelForm """

    class Meta:
        model = models.FileRepository
        fields = ['name']

    def __init__(self, request, parent, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.request = request
        self.parent = parent

    def clean_name(self):
        """ 钩子函数处理 “相同项目” “同级目录"  下 "文件夹" "重名"的问题  """
        # modelform中需要当前对象和父目录对象，重写__init__方法传递
        name = self.cleaned_data.get('name')
        query_set = models.FileRepository.objects.filter(name=name, project=self.request.login_user.project)
        # 如果是根目录 parent是空的
        # 如果不是根目录 parent是一个FileRepository对象
        if self.parent:
            exists = query_set.filter(parent=self.parent).exists()
        else:
            exists = query_set.filter(parent__isnull=True).exists()
        if exists:
            raise ValidationError('文件夹重名')

        return name


class FileModelForm(forms.ModelForm):
    """ 用于文件上传成功后将文件信息写入后台数据库 """

    etag = forms.CharField(label='ETag')

    class Meta:
        model = models.FileRepository
        exclude = ['project', 'file_type', 'update_user', 'update_datetime']

    def __init__(self, request, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.request = request

    def clean_file_path(self):
        return f'https://{self.cleaned_data["file_path"]}'

    """
        def clean(self):
        # 上传的文件名
        key = self.cleaned_data['key']
        # 上传文件成功后的标记，只有上传成功后才会有
        etag = self.cleaned_data['etag']
        # 上传文件大小
        size = self.cleaned_data['file_size']

        if not key or not etag:
            print('check1')
            return self.cleaned_data
        # COS验证上传的文件是否合法，验证etag，文件大小等
        from qcloud_cos.cos_exception import CosServiceError
        try:
            cos = CosTencent()
            result = cos.check_object(bucket_name=self.request.login_user.project.bucket_name,
                                      key=key)
        except CosServiceError as e:
            print('check2')
            self.add_error('key', '文件不存在')
            return self.cleaned_data
        cos_etag = result.get('ETag')
        if etag != cos_etag:
            print('check3')
            self.add_error('etag', 'ETag错误')

        cos_length = result.get('Content-Length')
        if int(size) != int(cos_length):
            print('check4')
            self.add_error('file_size', '文件大小不匹配')

        return self.cleaned_data
    """

